import {
  _decorator,
  resources,
  Component,
  Sprite,
  SpriteFrame,
  Asset,
  Texture2D,
  Node,
  director,
  tween,
  UITransform,
  Label,
} from 'cc';
import * as GIFuct from 'gifuct-js';
import { EventBus, TYPE } from './Utils/EventBus';
import { CommonData } from './Utils/CommonData';
const { ccclass, property } = _decorator;

const parseGIF = (GIFuct as any).default.parseGIF;
const decompressFrames = (GIFuct as any).default.decompressFrames;

@ccclass('Sun')
export class Sun extends Component {
  @property(Node)
  targetUI: Node = null!;

  private frameIndex = 0;

  protected async onLoad() {
    this.schedule(this.playNextFrame, 0.1);
    this.node.on(Node.EventType.TOUCH_END, this.onClick, this);
  }

  playNextFrame() {
    if (!CommonData.instance.sunFrames.length) return;
    this.node.getComponent(Sprite).spriteFrame =
      CommonData.instance.sunFrames[this.frameIndex];
    this.frameIndex =
      (this.frameIndex + 1) % CommonData.instance.sunFrames.length;
  }

  onClick() {
    if (!this.targetUI) {
      this.targetUI = director
        .getScene()
        ?.getChildByName('Canvas')
        ?.getChildByName('gameRoot')
        ?.getChildByName('SunCount');
    }
    // 获取到目标位置的世界坐标
    const targetWorldPos = this.targetUI.getWorldPosition();
    const parentNode = this.node.parent!;
    const targetLocalPos =
      parentNode
        .getComponent(UITransform)
        ?.convertToNodeSpaceAR(targetWorldPos) ?? targetWorldPos;

    // 将太阳缓动到目标位置
    tween(this.node)
      .to(0.6, { position: targetLocalPos })
      .call(() => {
        const sunCount = this.targetUI
          .getChildByName('CountLabel')
          .getComponent(Label).string;
        EventBus.emit(TYPE.SUN_CHANGE, Number(sunCount) + 1);
        this.node.destroy();
      })
      .start();
  }
}
